/*
 * CHTTPRetriever.cpp
 *
 *  Created on: 7 oct. 2009
 *      Author: digitalguru
 */

#include "CHTTPRetriever.h"
#include "CSocket.h"

CHTTPRetriever::~CHTTPRetriever()
{
}

CHTTPRetriever::CHTTPRetriever()
{
}

std::string CHTTPRetriever::GET(std::string URL)
{
	std::string Host = getHost(URL);
	std::string Page = getPage(URL);

	if(Page == std::string("")) Page = std::string("/index.html");

	std::string Request = "GET " + Page + " HTTP/1.0\r\n";
	Request += "Host: www." + Host + "\r\n";
	Request += "Accept: */*\r\n";
	Request += "Referer: " + URL + "\r\n";
	Request += "User-Agent: RSSReader\r\n\r\n\r\n";

	#ifdef DEBUG
		std::cout << "Retrieving HTTP..." << std::endl;
		std::cout << "URL : " << URL << std::endl;
		std::cout << "Host : " << Host << std::endl;
		std::cout << "Page : " << Page << std::endl;
		std::cout << "Request : " << Request << std::endl;
	#endif

	CSocket HTTPSocket(Host, 80);
	HTTPSocket.Connect();
	HTTPSocket.Send(Request);
	std::string Answer = std::string(HTTPSocket.Receive(65536));
	HTTPSocket.Disconnect();

	return getHTML(Answer);
}

std::string CHTTPRetriever::getHost(std::string URL)
{
	if(URL.substr(URL.length() - 1, 1) != std::string("/")) URL.append("/");

	if(URL.substr(0, 7) == std::string("http://")) URL.erase(0, 7);
	if(URL.substr(0, 4) == std::string("www.")) URL.erase(0, 4);
	URL.erase(URL.find_first_of('/'));

	return URL;
}

std::string CHTTPRetriever::getPage(std::string URL)
{
	std::string Host = getHost(URL);

	if(URL.length() > 7 && URL.substr(0, 7) == std::string("http://")) URL.erase(0, 7);
	if(URL.length() > 4 && URL.substr(0, 4) == std::string("www.")) URL.erase(0, 4);
	if(URL.length() > Host.length() && URL.substr(0, Host.length()) == Host) URL.erase(0, Host.length());

	if(URL == std::string("")) return std::string("/index.html");

	URL.erase(0, URL.find_first_of('/'));

	return URL;
}

std::string CHTTPRetriever::getHTML(std::string Response)
{
	return Response.erase(0, Response.find_first_of('<'));
}
